package lion.framework.core.web.views;

import java.io.IOException;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import lion.dev.lang.Lang;
import lion.framework.core.conf.Config;
import lion.framework.core.conf.ConfigManager;
import lion.framework.core.web.anno.ViewType;
import lion.framework.core.web.request.RequestModel;
import lion.json.Json;

/**
 * jsonp视图需要通过model.getString("callback"),HttpServletRequest.getAttribute(
 * "callback"), HttpServletRequest.
 * getParameter("callback")方式进行查找callback,如果未设置callback,则callback为"callback"<br/>
 * 通过model.get("json"),HttpServletRequest.getAttribute("callback")查找要转为json的对象
 *
 * <pre>
 * time   2013 2013-5-14 下午04:28:35
 * mail   hl_0074@sina.com
 * </pre>
 *
 * @author lion
 */
@ViewType("jsonp")
public class JSONPView implements IView {

	public static final String VIEW_TYPE = "jsonp";
	private String name;

	@Override
	public void render(HttpServletRequest request, HttpServletResponse response) throws Exception {

		String callback = Lang.nvl(request.getParameter("callback"), (String) request.getAttribute("callback"), "callback");
		Object json = request.getAttribute("json");
		if (json == null) {
			json = new RequestModel(request);
		}

		response.setHeader("Cache-Control", "no-cache,no-store,must-revalidate,max-age=0,proxy-revalidate,no-transform,pre-check=0,post-check=0,private");
		response.setHeader("Pragma", "no-cache");
		response.setHeader("Expires", "0");

		Config config = ConfigManager.getConfig("framework");
		response.setContentType("application/javascript;charset=" + config.getString("framework.sysencoding", "UTF-8"));
		try {
			response.getWriter().write(callback + "(" + Json.toJson(json) + ")");
		} catch (IOException e) {

		}
	}

	@Override
	public String getName() {

		return name;
	}

	@Override
	public String type() {

		return VIEW_TYPE;
	}

}
